/*
 * @(#)MD5.java Mar 31, 2008
 * 
 * Copyright 2007 by ChinanetCenter Corporation.
 *
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * ChinanetCenter Corporation ("Confidential Information").  You
 * shall not disclose such Confidential Information and shall use
 * it only in accordance with the terms of the license agreement
 * you entered into with ChinanetCenter.
 * 
 */
package com.cnc.bas.util;

import java.io.File;
import java.io.FileInputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;

/**
 * @author ����
 * @date Mar 31, 2008
 * @version 1.0
 */
public class MsgDigest
{

	/**
	 * ��ȡĳ���ַ��md5
	 * 
	 * @param s
	 * @return
	 */
	public final static String md5(String str)
	{

		try
		{

			MessageDigest md = MessageDigest.getInstance("MD5");

			md.update(str.getBytes());

			return getMd5String(md.digest());

		}
		catch (Exception e)
		{
			return null;
		}
	}

	/**
	 * ��ȡĳ���ļ���md5
	 * 
	 * @param file
	 * @return
	 */
	public final static String md5(File file)
	{

		try
		{

			MessageDigest md = MessageDigest.getInstance("MD5");

			DigestInputStream in = new DigestInputStream(new FileInputStream(
					file), md);

			byte[] buffer = new byte[8192];

			while (in.read(buffer) != -1)
				;

			return getMd5String(md.digest());

		}
		catch (Exception e)
		{
			return null;
		}
	}

	private static String getMd5String(byte[] bytes)
	{

		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };

		int j = bytes.length;

		char str[] = new char[j * 2];

		for (int i = 0, k = 0; i < j; i++)
		{
			byte byte0 = bytes[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}

		return new String(str);
	}
	
	public static void main(String[] args)
	{
		// TODO Auto-generated method stub
		//7cc0cb5bfc43aa198973e706f64c6978
		String src = "test.com.cntesttest.com.cn/aa.htm;test.com.cn/bb.htmimg.test.com.cn/dir1;img.test.com.cn/dir2";
		String md5 = MsgDigest.md5(src);
		System.out.println(md5);//b4c5e576a755dae50e1fa1afac5792b2


	}
}
